package com.damai.action.json;

import java.beans.IntrospectionException;
import java.lang.reflect.Field;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.citywithincity.api.entities.Customer;
import com.citywithincity.utils.ClassUtil;
import com.citywithincity.utils.StringUtils;
import com.damai.annotation.ParamValidate;
import com.damai.error.ApiError;
import com.damai.param.IParamValidate;
import com.damai.param.Rules;

class BeanParamGetter implements IParamGetter {
	private Class<?> type;
	private Field[] fields;
	private String name;
	private String[] requireMessages;
	private IParamValidate[] validates;
	
	
	public BeanParamGetter(String name,Class<?> type) throws IntrospectionException {
		this.type = type;
		this.name = name;
		fields = ClassUtil.getFields(type);
		requireMessages = new String[fields.length];
		validates = new IParamValidate[fields.length];
		
		int index = 0;
		for (Field field : fields) {
			field.setAccessible(true);
			ParamValidate validate = field.getAnnotation(ParamValidate.class);
			if(validate!=null){
				requireMessages[index]=StringUtils.isEmpty(validate.requireMessage()) ? null :validate.requireMessage(); 
				validates[index] = Rules.getValidate(validate.rule(),validate.message());
			}
			++index;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Object get(Map<String, Object> json) {
		try {
			final Field[] fields = this.fields;
			final Class<?> type = this.type;
			final int count = fields.length;
			final String name = this.name;
			final String[] requireMessages = this.requireMessages;
			final IParamValidate[] validates = this.validates;
			
			Map<String, Object> param = (Map<String, Object>) json.get(name);
			Object obj = type.newInstance(); // 创建 JavaBean 对象
			// 给 JavaBean 对象的属性赋值
			for(int i=0 ; i < count; ++i){
				Field field = fields[i];
				String propertyName = field.getName();
				// 下面一句可以 try 起来，这样当一个属性赋值失败的时候就不会影响其他属性赋值。
				Object value = param.get(propertyName);
				if(value==null){
					String requireMessage = requireMessages[i];
					if(!StringUtils.isEmpty(requireMessage)){
						throw new ApiError(requireMessage);
					}
				}
				IParamValidate paramValidate = validates[i];
				if(paramValidate!=null){
					paramValidate.validateParam(value);
				}
				field.set(obj, value);
			}
			
			if(obj instanceof IUserData){
				HttpServletRequest request = (HttpServletRequest) json.get("request");
				if(request != null){
					Customer customer = (Customer) request.getAttribute("customer");
					if(customer!=null){
						((IUserData)obj).setUserId(customer.getId());
					}
				}
				
			}
			
			return obj;
		} catch (Exception e) {
//			throw new ApiError("参数错误"+e.getMessage());
			throw new ApiError(e.getMessage());
		}
	}

}
